<template>
	<view class="content" :data-theme="themeVar" :style="{height: height + 'px'}">
		<view class="navigation">
			<eui-nav-bar title="设置客户代码" rightIcon="none" />
			<view class="card-input-box">
				<eui-card-input v-model="customerNo" title="客户代码" placeholder="请输入客户代码" type="text" :required="true"
					:rightIcon="true" rightIconType="clear" rightLastIcon="scan"
					autoStyle="borderRadius: 20rpx;border-radius: 20rpx" :rightLastIconColor="inputIconColor"
					alignType="left" :rightIconSize='40' :clearIconSize="14" rightIconColor="#666666"
					@iconClick="clickClear" @iconLastClick="clickScan" @confirm="onConfirm" />
			</view>
		</view>

		<view class="flex"><eui-button type="primary" title="添加" @buttonClick="add" class="primary-btn" /></view>
		<view class="privacy-policy" @click="onPrivacyPolicies">查看《隐私政策》</view>
		<view class="card" :style="{height: scrollHeight + 'px'}">
			<view class="title">客户列表</view>
			<scroll-view class="scroll-view scroll-Y" :style="{height: scrollHeight-65 + 'px'}" scroll-y>
				<view class="template-list" v-for="(item, index) in customerList" :key="item.ID"
					@click="onClickList(item, index)" @longpress="openList(item)">

					<view class="iconfont icon-kehuliebiao"></view>
					<view class="right">
						<view class="right-top">
							<text class="tips-tag" v-if="customerObject.ID == item.ID">当前</text>
							<text class="card-item-title">{{ item.EnjoyMain.c_name }}</text>
						</view>
						<view class="right-bottom">
							<view class="flex_1">
								<text class="item-label">客户代码</text>
								<text class="item-content">{{ item.EnjoyMain.c_cloud_id }}</text>
							</view>
							<view class="flex_1">
								<text class="item-label">主应用</text>
								<text class="item-content">{{ item.EnjoyMain.c_application }}</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { reactive, ref, onMounted, computed } from 'vue';
	import { storeToRefs } from 'pinia';
	import enjoy from '../../../common/enjoy.js'
	import service from '../../../common/service';
	import { useLoginStore } from '../../../store/modules/useLoginStore';
	import apps from '../app';
	import { useThemeStore } from '../../../store/themeStore';
	import EuiNavBar from '@enjoy/mobile/components/navbar/navbar.vue';
	import EuiButton from '@enjoy/mobile/components/button/button.vue';
	import EuiCardInput from '@enjoy/mobile/components/cardinput/cardinput.vue';

	const themeStore = useThemeStore(); // 主题
	const { theme } = storeToRefs(themeStore)
	const LoginStore = useLoginStore();

	let _theme = theme.value.split('-').pop();
	const themeVar = ref(_theme);
	const inputIconColor = computed(() => {
		return _theme === 'blue' ? '#02B7E6' : '#FF6430';
	});


	interface ICustomerApplication {
		c_cloud_id : string;
		c_application : string;
		c_ismain_app : string;
		c_name : string;
		c_status : string;
		c_modified_user : string;
		c_modified_dt : any;
		c_note : string;
		c_mobile_service_ip : string;
		c_request_http_type : string;
		c_is_hiddenid : string;
	}

	// 定义接口描述对象的结构
	interface ICustomer {
		EnjoyMain ?: ICustomerApplication;
		ID ?: string;
		EnjoyCRM ?: ICustomerApplication;
		EnjoyMall ?: ICustomerApplication;
		EnjoyMallSCM ?: ICustomerApplication;
		EnjoyMPM ?: ICustomerApplication;
		EnjoyOA ?: ICustomerApplication;
		EnjoyRMIS ?: ICustomerApplication;
	}

	const customerNo = ref<string>('');
	const customerList = ref<ICustomer[]>([]);
	let customerObject = reactive<ICustomer>({});

	const scrollHeight = ref<number>(0);

	const add = () => {
		/**
		 * 客户端对账号信息进行一些必要的校验。
		 * 实际开发中，根据业务需要进行处理，这里仅做示例。
		 */
		if (customerNo.value.length < 5) {
			service.enjoyShowToast('客户代码最短为 5 个字符!');
			return;
		}
		const AmapArray = service.getStorageSync('MobileAmap')
		const ObjectData = {
			IsNotPage: true,
			SqlWhereTail: ' where c_cloud_id = \'' + customerNo.value + '\' ',
			Tag: AmapArray,
		};
		apps.GetCloudCustDef(ObjectData, (res) => {

			service.setStorageSync('MobileAmap', JSON.stringify([]));
			let listObj : ICustomer = {};
			if (res && res.ObjectData && res.ObjectData.ReturnObject && res.ObjectData.ReturnObject.length > 0) {
				let ReturnObject = res.ObjectData.ReturnObject;
				for (let i in ReturnObject) {
					let item = ReturnObject[i];
					listObj.ID = item.c_cloud_id;
					if (item.c_ismain_app === '是') {
						listObj.EnjoyMain = {
							...item,
							c_mobile_service_ip: item.c_mobile_service_ip + '/mbmv5',
						};
					}
					listObj[item.c_application as keyof ICustomer] = {
						...item,
					};
				}
			} else {
				service.enjoyShowToast('客户配置不存在！');
				return;
			}
			if (listObj.EnjoyMain) {
				customerObject = listObj;
				const exists = customerList.value.some((item) => item.ID === listObj.ID);
				if (!exists) {
					customerList.value.push(listObj);
				}

				service.setStorageSync('CUSTOMERLIST', customerList.value);
				service.setStorageSync("CUSTOMEROBJECT", customerObject);
				console.log('================ reg ====================: ', customerObject)
				LoginStore.setCustomer(customerObject);

			} else {
				service.enjoyShowToast('未配置主应用！');
			}
		}, (err) => {
			console.log(err, '失败了');
		});
	};

	// MARK: - 客户列表点击事件
	const onClickList = (item : any, index : number) => {
		service.setStorageSync("CUSTOMEROBJECT", item);
		LoginStore.setCustomer(item);
		setTimeout(() => {
			// #ifdef APP-PLUS
			plus.runtime.restart();
			// #endif 

			// TODO 调试模式, 有bug, pinia State未更新选择后的ip 后期删除

			uni.reLaunch({
				url: '/pages/MainViews/index/index'
			});

		}, 500)
	};
	// 长按删除
	const openList = (event : any) => {
		uni.showModal({
			title: ' 提示',
			content: '确认从本地删除选中的客户配置？',
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					customerList.value = customerList.value?.filter(item => item.ID !== event.ID) || [];
					if (!customerList.value.length) {
						customerObject = {};
						service.setStorageSync("CUSTOMEROBJECT", {});
					} else if (event.ID == customerObject?.ID) {
						customerNo.value = '';
						customerObject = {};
						service.setStorageSync("CUSTOMEROBJECT", {});
					}
					service.setStorageSync('CUSTOMERLIST', customerList.value);
				}
			},
		});
	};
	// 清空内容
	const clickClear = (event : any) => {
		customerNo.value = "";
	};

	// 回车
	const onConfirm = (event : any) => {
		if (customerNo.value) {
			add();
		}
	};
	// 隐私跳转
	const onPrivacyPolicies = () => {
		uni.navigateTo({
			url: '/packages/MainViews/main/pravicypolicies'
		});
	};

	const height = ref(750);
	// 初始化滚动区域高度
	const initScrollView = () => {
		uni.getSystemInfo({
			success: (res) => {
				height.value = res.windowHeight;
				const h = res.windowHeight - res.safeAreaInsets.bottom;
				uni.createSelectorQuery().select('.card').boundingClientRect(data => {
					if (data) {
						scrollHeight.value = h - data.top - 10;
					}
				}).exec();
			}
		})

	}

	const initCustomerNo = ref(''); // 缓存初始化客户代码, 用于返回判断是否重启应用
	const navBarClickLeft = () => {
		if (customerList.value.length === 0) {
			service.enjoyShowToast('请先设置客户代码!')
		} else if (!customerObject.ID) {
			service.enjoyShowToast('请先选择当前客户!')
		} else if (customerObject.ID !== initCustomerNo.value) {
			// #ifdef APP-PLUS
			plus.runtime.restart();
			// #endif

			uni.reLaunch({
				url: '/pages/MainViews/index/index'
			});
		} else {
			uni.navigateBack();
		}
	}

	// 扫码
	const clickScan = () => {
		uni.scanCode({
			success: function (res) {
				if (res.result) {
					let scanRet = res.result;
					if (scanRet.indexOf("{\"ds\"") === 0) {
						service.setStorageSync('MobileAmap', JSON.stringify([]));
						const defs = JSON.parse(scanRet);
						if (defs && defs.ds && defs.ds.length > 0) {
							let listObj = {
								EnjoyMain: {} as ICustomerApplication,
								ID: "EIInnerNet",
							};

							//默认第１个为主应用
							listObj.EnjoyMain = {
								c_cloud_id: "EIInnerNet",
								c_application: defs.ds[0].u.split(',')[1],
								c_ismain_app: '是',
								c_name: defs.n,
								c_status: '已启用',
								c_modified_user: '陈涛',
								c_modified_dt: '2023-08-23 19:19:25',
								c_note: '',
								c_mobile_service_ip: defs.ds[0].u.split(',')[0] + '/mbmv5',
								c_request_http_type: defs.ds[0].u.split(',')[0].indexOf('https') >= 0 ? 'https' : 'http',
								c_is_hiddenid: '是'
							};
							for (let i in defs.ds) {
								let item = defs.ds[i];
								listObj[item.u.split(',')[1]] = {
									c_cloud_id: "EIInnerNet",
									c_application: item.u.split(',')[1],
									c_ismain_app: i == '0' ? '是' : '否',
									c_name: defs.n,
									c_status: '已启用',
									c_modified_user: '陈涛',
									c_modified_dt: '2023-08-23 19:19:25',
									c_note: '',
									c_mobile_service_ip: item.u.split(',')[0],
									c_request_http_type: item.u.split(',')[0].indexOf('https') >= 0 ? 'https' : 'http',
									c_is_hiddenid: '是'
								};
							}

							if (listObj.EnjoyMain) {

								customerObject = reactive(listObj);
								customerNo.value = "EIInnerNet"
								customerList.value.push(listObj);
								customerList.value = enjoy.uniqueArray(customerList.value, 'ID');
								service.setStorageSync("CUSTOMERLIST", customerList.value);
								service.setStorageSync("CUSTOMEROBJECT", customerObject);
							} else {
								uni.showToast({
									duration: 3500,
									icon: 'none',
									title: '未配置主应用！'
								});
							}
						} else {
							uni.showToast({
								duration: 3500,
								icon: 'none',
								title: '未识别到二维码内容，请重试（offLine）！'
							});
						}
					} else {
						customerNo.value = scanRet;
						add();
					}
				} else {
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: '未识别到二维码内容，请重试！'
					});
				}
			}
		});
	}

	onLoad(() => {
		const _localCustList = service.getStorageSync('CUSTOMERLIST');
		const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");

		if (_localCustList) {
			customerList.value = _localCustList ? _localCustList : [];
			customerObject = CUSTOMEROBJECT ? CUSTOMEROBJECT : {};
		}

		if (customerObject && customerObject.ID) {
			customerNo.value = customerObject.ID;
			initCustomerNo.value = JSON.parse(JSON.stringify(customerObject.ID));
		}
	});

	onMounted(() => {
		initScrollView()
	});

	defineExpose({
		navBarClickLeft
	})
</script>
<style>
	.card-input-box .m-card-input-view[data-v-18b171cf] {
		margin: auto;
		border-radius: 20rpx;
	}
</style>
<style lang="scss" scoped>
	@mixin flex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	@mixin flex-between {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	@mixin flex-start {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.flex {
		display: flex;
	}

	.flex_1 {
		flex: 1;
	}

	.content {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background: #F2F2F2;

		.primary-btn {
			margin: 40rpx 0 0 50%;
			transform: translate(-50%);
		}

		.card-input-box {
			padding: 0 20rpx;
			background: linear-gradient(180deg, rgba(242, 242, 242, 0) 0%, #F2F2F2 100%);

			::v-deep .m-card-input-title {
				display: flex;
			}
		}
	}

	.navigation {
		font-family: PingFangSC, PingFang SC;
		@include background-gradient(theme);
	}

	.card {
		margin: 40rpx 20rpx 20rpx;
		width: calc(100% - 40rpx);
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 0 28rpx 28rpx;
		box-sizing: border-box;

		.title {
			height: 90rpx;
			line-height: 90rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
		}

		.template-list {
			padding: 20rpx 0;
			box-sizing: border-box;
			border-bottom: 1rpx solid #EEEEEE;
			display: flex;
			justify-content: flex-start;
			align-items: center;
		}

		.iconfont {
			margin-right: 20rpx;
			width: 64rpx;
			height: 64rpx;
			@include flex-center;
			color: #FFFFFF;
			border-radius: 50%;
			@include background-gradient(theme);
		}

		.right {
			width: 0;
			flex: 1;
			@include flex-between;
			flex-direction: column;
			align-items: flex-start;
		}

		.tips-tag {
			display: inline-block;
			margin-right: 8rpx;
			width: 60rpx;
			height: 36rpx;
			font-weight: 500;
			text-align: center;
			border-radius: 6rpx;
			border: 1rpx solid;
			line-height: 36rpx;
			font-size: 22rpx;
			@include themeText("themeText");
			@include background_color("lightBgc");
			@include borderColor('lightBorderColor');
		}

		.right-bottom {
			@include flex-between;
			width: 100%;
		}

		.card-item-title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 30rpx;
			color: #000000;
		}

		.item-label {
			margin-right: 16rpx;
			color: #888888;
			font-size: 24rpx;
			font-family: PingFangSC, PingFang SC;
		}

		.item-content {
			font-family: PingFangSC, PingFang SC;
			font-size: 24rpx;
			color: #000000;
		}

	}

	.privacy-policy {
		width: 100%;
		margin: 20rpx auto 0;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		text-align: center;
		@include themeText("themeText");
	}
</style>